<template>
  <div>
    <h2>ROS 状态: {{ connected ? '✅ 已连接' : '❌ 未连接' }}</h2>
    <button class="" @click="publish">发布消息</button>
    <p>订阅到: {{ msg }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Ros, Topic } from 'roslib'

interface RosString {
  data: string
}

const connected = ref<boolean>(false)
const msg = ref<string>('')

const ros = new Ros({
  url: 'ws://localhost:9090'
})

ros.on('connection', () => {
  connected.value = true
})

ros.on('close', () => {
  connected.value = false
})

// 订阅话题
let chatter: Topic<RosString>

onMounted(() => {
  chatter = new Topic<RosString>({
    ros,
    name: '/chatter',
    messageType: 'std_msgs/String'
  })

  chatter.subscribe((m) => {
    msg.value = m.data
  })
})

onUnmounted(() => {
  chatter.unsubscribe()
})

const publish = () => {
  chatter.publish({ data: 'Hello from Vue3 + ROSLIBJS v1.4!' })
}
</script>
